package com.open.capacity.task.service.impl;

import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.task.dao.TaskAreaDao;
import com.open.capacity.task.model.TaskArea;
import com.open.capacity.task.service.TaskAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;

@Service
public class TaskAreaServiceImpl implements TaskAreaService {
    @Autowired
    TaskAreaDao taskAreaDao;

    @Override
    public Result findTaskArea(Map<String, Object> params) {

        return Result.succeed(taskAreaDao.findTaskArea(params),"查询成功");
    }

    @Override
    public Result addTaskArea(TaskArea taskArea) {
        boolean isExist = isExist(taskArea.getAreaValue(),null);
        if (isExist){
            return Result.failed("该areaValue已存在");
        }
        Integer addResult = taskAreaDao.addTaskArea(taskArea);
        if (addResult == 1){
            return Result.succeed("添加成功");
        }
        return Result.failed("添加失败,请重试");
    }

    @Override
    public Result updateTaskArea(TaskArea taskArea) {
        boolean isExist = isExist(taskArea.getAreaValue(),taskArea.getId());
        if (isExist){
            return Result.failed("该areaValue已存在");
        }
        Integer updateResult = taskAreaDao.updateTaskArea(taskArea);
        if (updateResult == 1){
            return Result.succeed("修改成功");
        }
        return Result.failed("修改失败,请重试");
    }

    @Transactional
    @Override
    public Result deleteTaskArea(List<Integer> taskAreaIds) {
        if (taskAreaIds.isEmpty()){
            return Result.failed("请选择需要删除的行");
        }
        Integer deleteResult = 0;
        for (Integer taskAreaId : taskAreaIds) {
            deleteResult += taskAreaDao.deleteTaskArea(taskAreaId);
        }

        //删除的个数错误
        if (deleteResult != taskAreaIds.size()){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failed("未知错误,删除失败");
        }
        return Result.succeed("删除成功");
    }

    private boolean isExist(String areaValue, Integer id){
        return taskAreaDao.isExist(areaValue,id) > 0;
    }
}
